<?php
declare (strict_types = 1);

namespace app\command\logic;

use app\command\logic\BaseLogic;
use think\console\Output;

/**
 * 统计-商家-数据
 * php think cli stats_shop_data --msg='{"days":30}'
 */
class CliStatsShopDatqLogic extends BaseLogic implements CliInterface
{

    /**
     * 入口方法
     * {@inheritdoc}
     */
    public function run(Output $output, array $msg): bool
    {
        $insertData = [];
        $date       = isset($msg['date']) ? ($msg['date'] == 'today' ? date('Y-m-d') : $msg['date']) : null;
        if ( ! empty($date)) {
            self::dataForMember($date);
        } else {
            $days = intval($msg['days'] ?? 1);
            for ($i = 1; $i <= $days; $i++) {
                $date = date('Y-m-d', strtotime("-$i days"));
                self::dataForMember($date);
            }
        }
        return true;
    }

    private static function dataForMember($date)
    {
        $end = $date . ' 23:59:59';

        // status 0待支付 1待发货 2待收款 3已收货 4已完成 5退款中 6团款成功
        $field = [
            'shop_id',
            // 'amount', // '会员总数',
            // 'view_count', // '访问人数',
            // 'new_count', // '新增加会员数',
            'count(distinct user_id) order_member_count', // '下单会员数',
            'count(*) order_count', // '订单数量',
            'sum(CASE WHEN pay_at is null THEN 0 ELSE 1 END) AS pay_order_count', // '支付订单数',
            'sum(CASE WHEN pay_at is null THEN 0 ELSE pay_price END) AS pay_price', // `
        ];
        $rows = \think\facade\Db::table('order_shop')
            ->field($field)
            ->where('deleted', 0)
            ->whereBetweenTime('create_at', $date, $end)
            ->group('shop_id')
            ->select()->toArray();

        if (empty($rows)) {
            return true;
        }
        // echo \think\facade\Db::table('order_shop')->getlastsql();
        // var_dump($rows);exit;

        // 统计店铺会员
        $field2 = [
            'shop_id',
            'user_id',
            'create_at',
        ];
        $rows2 = \think\facade\Db::table('order_shop')
            ->field($field2)
            ->where('deleted', 0)
            ->whereBetweenTime('create_at', $date, $end)
            ->select()->toArray();
        foreach ($rows2 as $row) {
            $at = \think\facade\Db::table('shop_member')
                ->where('shop_id', $row['shop_id'])
                ->where('user_id', $row['user_id'])
                ->value('create_at');
            if (empty($at)) {
                \think\facade\Db::table('shop_member')->insert([
                    'shop_id'   => $row['shop_id'],
                    'user_id'   => $row['user_id'],
                    'create_at' => $row['create_at'],
                ]);
            } elseif (strtotime($at) > strtotime($row['create_at'])) {
                $at = \think\facade\Db::table('shop_member')
                    ->where('shop_id', $row['shop_id'])
                    ->where('user_id', $row['user_id'])
                    ->update([
                        'update_at' => date('Y-m-d H:i:s'),
                        'create_at' => $row['create_at'],
                    ]);
            }
        }
        // end 统计店铺会员

        $insertData = [];
        foreach ($rows as $row) {
            $row['date']   = $date;
            $row['amount'] = \think\facade\Db::table('shop_member')
                ->where('shop_id', $row['shop_id'])
                ->where('deleted', 0)
                ->count();
            $row['new_count'] = \think\facade\Db::table('shop_member')
                ->where('shop_id', $row['shop_id'])
                ->where('deleted', 0)
                ->whereBetweenTime('create_at', $date, $end)
                ->count();

            $row['view_count'] = \think\facade\Db::table('member_oplog')
                ->whereLike('api', '/api/shop/shopDetail%')
                ->whereLike('params', '%_shop_' . $row['shop_id'] . '_shop_%')
                ->whereBetweenTime('create_at', $date, $end)
                ->count('distinct user_id');
            // echo \think\facade\Db::table('member_oplog')->getlastsql();exit;
            $insertData[] = $row;
        }
        \think\facade\Db::table('stats_shop_data')
            ->replace()
            ->insertAll($insertData);
        return true;
    }
}
